package com.logic.landseaserver.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.logic.common.domain.Code;
import com.logic.common.exception.BusinessException;
import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.enums.BillTypeEnum;
import com.logic.landseaserver.common.exception.LandseaBusinessException;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.domain.CodeReference;
import com.logic.landseaserver.domain.Estate;
import com.logic.landseaserver.domain.PeopleInfo;
import com.logic.landseaserver.domain.Project;
import com.logic.landseaserver.domain.RoomType;
import com.logic.landseaserver.persistence.read.CodeReferenceReadMapper;
import com.logic.landseaserver.persistence.read.EstateReadMapper;
import com.logic.landseaserver.persistence.read.ProjectReadMapper;
import com.logic.landseaserver.persistence.read.RoomReadMapper;
import com.logic.landseaserver.persistence.read.RoomTypeReadMapper;
import com.logic.landseaserver.persistence.write.CodeReferenceWriteMapper;
import com.logic.landseaserver.persistence.write.EstateWriteMapper;
import com.logic.landseaserver.persistence.write.ProjectWriteMapper;
import com.logic.landseaserver.service.Action;
import com.logic.landseaserver.service.IContractService;
import com.logic.landseaserver.service.IProjectService;
import com.logic.landseaserver.ws.dto.ContractDTO;
import com.logic.landseaserver.ws.dto.ExpenseDTO;
import com.logic.landseaserver.ws.dto.FeePrjDTO;
import com.logic.landseaserver.ws.dto.KeeperDTO;
import com.logic.landseaserver.ws.dto.ProjectAppartmentDTO;
import com.logic.landseaserver.ws.dto.ProjectDTO;
import com.logic.landseaserver.ws.dto.ProjectDetailDTO;
import com.logic.landseaserver.ws.dto.ProjectDetailForFrontDTO;
import com.logic.landseaserver.ws.dto.ProjectReqDTO;
import com.logic.system.domain.Address;
import com.logic.system.domain.Configuration;
import com.logic.system.domain.SystemFile;
import com.logic.system.domain.UserProject;
import com.logic.system.persistence.read.AddressReadMapper;
import com.logic.system.persistence.read.CodeReadMapper;
import com.logic.system.persistence.read.ConfigurationReadMapper;
import com.logic.system.persistence.write.AddressWriteMapper;
import com.logic.system.persistence.write.UserWriteMapper;
import com.logic.system.service.ICodeService;
import com.logic.system.service.impl.FileService;


/**
 * @Author: Wells.Wei
 * @Date: 2017/4/12
 * @Description: 租赁项目接口实现类
 */
@Service
public class ProjectServiceImpl implements IProjectService, EnvironmentAware {

    private static final String COUNTRY_CODE = "_A11";

    private static final String TYPE = "LT1";

    private static final Logger LOG = LoggerFactory.getLogger(ProjectServiceImpl.class);

    @Autowired
    private ProjectReadMapper projectReadMapper;

    @Autowired
    private ProjectWriteMapper projectWriteMapper;

    @Autowired
    private EstateReadMapper estateReadMapper;

    @Autowired
    private EstateWriteMapper estateWriteMapper;

    @Autowired
    private AddressReadMapper addressReadMapper;

    @Autowired
    private AddressWriteMapper addressWriteMapper;

    @Autowired
    private CodeReferenceReadMapper codeReferenceReadMapper;

    @Autowired
    private CodeReferenceWriteMapper codeReferenceWriteMapper;

    @Autowired
    private CodeReadMapper codeReadMapper;

    @Autowired
    private RoomTypeReadMapper roomTypeReadMapper;

    @Autowired
    private ConfigurationReadMapper configurationReadMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private ICodeService codeService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    private RoomReadMapper roomReadMapper;

    @Autowired
    private UserWriteMapper userWriteMapper;

    @Autowired
    private IContractService contractServiceImpl;

    private static RelaxedPropertyResolver propertyResolver;
    private static final String ENV_FILE_PATH = "logic.file.path.";
    private static final String LOCAL_PATH = "local";
    private static final String REMOTE_PATH = "remote";


    @Override
    public void setEnvironment(Environment environment) {
        propertyResolver = new RelaxedPropertyResolver(environment, ENV_FILE_PATH);
    }


    private String getUrl(String str) throws BusinessException {
        StringBuffer url = propertyResolver.getProperty(REMOTE_PATH, StringBuffer.class, null);
        String urlStr = url.toString();
        //updated by Daniel for keeping the icon url corrected.
//		if(urlStr.indexOf("/u")>=0){
//            urlStr = urlStr.substring(0, urlStr.indexOf("/u"));
//        }

        urlStr = urlStr + str;
        return urlStr;
    }


    @Override
    public int insert(Object o) throws BusinessException {

        return validateForInsert(o) ? projectWriteMapper.insertSelective((Project) o) : -1;
    }

    @Override
    public Project get(Integer integer) throws BusinessException {
        return projectReadMapper.selectByPrimaryKey(integer);
    }

    @Override
    public void update(Object o) throws BusinessException {

        if (validateForUpdate(o)) {
            //增加项目状态日志 by Daniel
            Project prj = projectReadMapper.selectByPrimaryKey(((Project) o).getId());
            String oldStatus = prj.getStatus(); //LPA1-4 草稿/发布/关闭/下线
            String oldPublicStatus = prj.getPublicStatus(); //LPAP1-2 官网发布/官网未发布

            projectWriteMapper.updateByPrimaryKeySelective((Project) o);

            String status = ((Project) o).getStatus(); //LPA1-4 草稿/发布/关闭/下线
            String publicStatus = ((Project) o).getPublicStatus(); //LPAP1-2 官网发布/官网未发布

            try {
                if(!oldStatus.equalsIgnoreCase(status) || !publicStatus.equalsIgnoreCase(publicStatus)) {
                    LOG.info("用户名:"+SecurityUtils.getCurrentLogin().getUserName()+",用户编号:"
                            +SecurityUtils.getCurrentLogin().getUserId()
                            +",修改了项目-项目编码:"+((Project) o).getPrjCode()
                            +",状态:"+codeService.getCode(oldStatus).getCodeDescZh() + ">>>"+codeService.getCode(status).getCodeDescZh()
                            +",官网状态:"+codeService.getCode(oldPublicStatus).getCodeDescZh() + ">>>"+codeService.getCode(publicStatus).getCodeDescZh());
                }
            }catch(Exception e){}

        }
    }

    @Override
    public void delete(String ids) throws BusinessException {

        String[] idArr = ids.split(",");
        for (String id : idArr) {
            //删除项目之前判断该项目是否有关联的房间信息
            List<ProjectAppartmentDTO> paList = roomReadMapper.selectByPrjId(Integer.parseInt(id));
            if (paList.size() > 0) {
                throw new LandseaBusinessException("请先删除该项目下的房间。");
//         		for(int i=0;i<paList.size();i++){
//         			ProjectAppartmentDTO pad = paList.get(i);
//         			String status = pad.getAppendStatus();
//         			if("LRB1".equals(status)){
//         				 throw new LandseaBusinessException("房间有空置状态，请确认。");
//         			}
//         		}
            }
            projectWriteMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
    }

    @Override
    @Action(name = "项目查询")
    public List<ProjectDTO> query(QueryUtil queryUtil) {

        List<ProjectDTO> result = projectReadMapper.getProjectRespList(queryUtil);
        return result;
    }

    /**
     * 添加项目信息 事务已添加
     *
     * @param projectReqDTO
     * @throws BusinessException
     * @throws LandseaException 
     */
    @Transactional(rollbackFor = {LandseaBusinessException.class,LandseaException.class, Exception.class})
    @Override
    public void addOrEditProject(ProjectReqDTO projectReqDTO) throws BusinessException,LandseaException {
        if (validateForInsert(projectReqDTO)) {
            Integer userId = SecurityUtils.getCurrentLogin().getUserId();
            if (userId == null) {
                throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
            }
            Integer projectid = projectReqDTO.getPrjId();
            Address address = new Address();
            Project project = new Project();
            Estate estate = new Estate();
            List<String> codeList = new ArrayList<>();  //存放装修风格/设备/竞品信息等信息的code
            String styleCodeStr = projectReqDTO.getStyle();
            String[] emptyArray = {};
            String[] styleCodeArr = StringUtils.isEmpty(styleCodeStr) ? emptyArray : styleCodeStr.split(",");

            String facilityCodeStr = projectReqDTO.getFacility();
            String[] facilityCodeArr = StringUtils.isEmpty(facilityCodeStr) ? emptyArray : facilityCodeStr.split(",");

/*          String competitionCodeStr = projectReqDTO.getCompetition();
            String[] competitionCodeArr = StringUtils.isEmpty(competitionCodeStr) ? emptyArray : competitionCodeStr.split(",");
*/
            String serviceCodeStr = projectReqDTO.getService();
            String[] serviceCodeArr = StringUtils.isEmpty(serviceCodeStr) ? emptyArray : serviceCodeStr.split(",");

            codeList.addAll(Arrays.asList(serviceCodeArr));
            codeList.addAll(Arrays.asList(facilityCodeArr));
            /*codeList.addAll(Arrays.asList(competitionCodeArr));*/
            codeList.addAll(Arrays.asList(styleCodeArr));

            if (projectid != null && projectid > 0) {   //编辑项目
                project = projectReadMapper.selectByPrimaryKey(projectid);
                address = addressReadMapper.selectByPrimaryKey(project.getAddressId());
                //项目地址
                setAddressByProjectReqDTO(address, projectReqDTO, userId);
                addressWriteMapper.updateByPrimaryKeySelective(address);

                setProjectByProjectReqDTO(project, projectReqDTO, userId);
                projectWriteMapper.updateByPrimaryKeySelective(project);
                
                // 账户费项已换成其他处理方式 mod by aaron 2017-12-25
                /* if (null != projectReqDTO.getCostType())
                {
                    prepaymentService.editBalanceType(projectid,projectReqDTO.getCostType());
                }*/
                
                List<Estate> estateList = estateReadMapper.selectByProjectid(projectid);
                //暂时只有一个小区
                estate = estateList.get(0);
                setEstateByProjectReqDTO(estate, projectReqDTO, userId);
                estateWriteMapper.updateByPrimaryKeySelective(estate);

                facilityCodeStr = projectReqDTO.getFacility();
                List<Map<String, Object>> currentServiceCodeList = codeReferenceReadMapper.getCodeRefByPCode(projectid, "_LPD", TYPE);//获取装修风格_LPC/设备_LD code
                List<Map<String, Object>> currentStyleCodeList = codeReferenceReadMapper.getCodeRefByPCode(projectid, "_LPC", TYPE);//获取装修风格_LPC/设备_LD code
                List<Map<String, Object>> currentFacilityCodeList = codeReferenceReadMapper.getCodeRefByPCode(projectid, "_LDD", TYPE); //设备_LD code
//                List<Map<String, Object>> currentCompetitionCodeList = codeReferenceReadMapper.getCodeRefByPCode(projectid, "_LPE", TYPE);//竞品信息_LPE等信息 code
                List<Map<String, Object>> currentCodeList = new ArrayList<>();
                currentCodeList.addAll(currentStyleCodeList);
                currentCodeList.addAll(currentFacilityCodeList);
//                currentCodeList.addAll(currentCompetitionCodeList);
                currentCodeList.addAll(currentServiceCodeList);

                //删除取消的标签
                Iterator<Map<String, Object>> iterator = currentCodeList.iterator();
                while (iterator.hasNext()) {
                    String ss = (String) iterator.next().get("code");
                    if (!codeList.contains(ss)) {
                        iterator.remove();
                        codeReferenceWriteMapper.deleteByIdAndCode(projectid, ss, TYPE);
                    }
                }
                Iterator<String> it1 = codeList.iterator();
                while (it1.hasNext()) {
                    String s = it1.next();
                    for (Map<String, Object> m : currentCodeList) {
                        if (m.get("code").equals(s)) {
                            it1.remove();
                        }
                        continue;
                    }
                }
                // PRRO1   管家，PRRO2   店长，PRRO3   城市经理，PRRO4   系统
                //编辑管家
                if ("".equals(projectReqDTO.getHousekeeperId())
                        && null == projectReqDTO.getHousekeeperId()) {
                    UserProject upHouse = new UserProject();
                    upHouse.setPrjId(projectReqDTO.getPrjId());
                    upHouse.setUserId(projectReqDTO.getHousekeeperId());
                    upHouse.setPrjRole("PRRO1");
                    upHouse.updateCommonInfo(userId);
                    userWriteMapper.insertUserProjectSelective(upHouse);
                } else {
                    UserProject upHouse = new UserProject();
                    upHouse.setPrjId(projectReqDTO.getPrjId());
                    upHouse.setUserId(projectReqDTO.getHousekeeperId());
                    upHouse.setPrjRole("PRRO1");
                    upHouse.updateCommonInfo(userId);
                    userWriteMapper.updateByUserProByUserPrj(upHouse);
                }

                //编辑店长
                if ("".equals(projectReqDTO.getInChargeUserId())
                        && null == projectReqDTO.getInChargeUserId()) {
                    UserProject upCharge = new UserProject();
                    upCharge.setPrjId(projectReqDTO.getPrjId());
                    upCharge.setUserId(projectReqDTO.getInChargeUserId());
                    upCharge.setPrjRole("PRRO2");
                    upCharge.updateCommonInfo(userId);
                    userWriteMapper.insertUserProjectSelective(upCharge);
                } else {
                    UserProject upCharge = new UserProject();
                    upCharge.setPrjId(projectReqDTO.getPrjId());
                    upCharge.setUserId(projectReqDTO.getInChargeUserId());
                    upCharge.setPrjRole("PRRO2");
                    upCharge.updateCommonInfo(userId);
                    userWriteMapper.updateByUserProByUserPrj(upCharge);
                }

                //编辑区域经理
                if ("".equals(projectReqDTO.getDistrictUserId()) &&
                        null == projectReqDTO.getDistrictUserId()) {
                    UserProject upDistrict = new UserProject();
                    upDistrict.setPrjId(projectReqDTO.getPrjId());
                    upDistrict.setUserId(projectReqDTO.getDistrictUserId());
                    upDistrict.setPrjRole("PRRO3");
                    upDistrict.updateCommonInfo(userId);
                    userWriteMapper.insertUserProjectSelective(upDistrict);
                } else {
                    UserProject upDistrict = new UserProject();
                    upDistrict.setPrjId(projectReqDTO.getPrjId());
                    upDistrict.setUserId(projectReqDTO.getDistrictUserId());
                    upDistrict.setPrjRole("PRRO3");
                    upDistrict.updateCommonInfo(userId);
                    userWriteMapper.updateByUserProByUserPrj(upDistrict);
                }

            } else { //新建项目
                //项目地址
                address.setCountry(COUNTRY_CODE);
                setAddressByProjectReqDTO(address, projectReqDTO, userId);

                Code code = codeReadMapper.selectByPrimaryKey(projectReqDTO.getAreaCode());
                address.setCreatedBy(userId);
                addressWriteMapper.insertSelective(address);

                int addressid = address.getId();
                setProjectByProjectReqDTO(project, projectReqDTO, userId);
                project.updateCommonInfo(userId);
                project.setAddressId(addressid);
                projectWriteMapper.insertSelective(project);
                projectid = project.getId();
                Integer maxProCode = projectReadMapper.getMaxProCode(code.getOther1());
                //项目编码生成策略 城市编码 + 流水
                // String projectCode = code.getOther1() + (projectid < 10 ? "0" + projectid : projectid) + "";
                String projectCode = code.getOther1().trim() + new DecimalFormat("00").format(maxProCode + 1);
                project.setPrjCode(projectCode);
                projectWriteMapper.updateByPrimaryKeySelective(project);
                setEstateByProjectReqDTO(estate, projectReqDTO, userId);
                estate.setPrjId(projectid);
                estateWriteMapper.insertSelective(estate);
                // PRRO1   管家，PRRO2   店长，PRRO3   城市经理，PRRO4   系统
                //增加管家
                if (projectReqDTO.getHousekeeperId() != null) {
                    UserProject upHouse = new UserProject();
                    upHouse.setPrjId(projectid);
                    upHouse.setUserId(projectReqDTO.getHousekeeperId());
                    upHouse.setPrjRole("PRRO1");
                    userWriteMapper.insertUserProjectSelective(upHouse);
                }

                //增加店长
                if (projectReqDTO.getInChargeUserId() != null) {
                    UserProject upCharge = new UserProject();
                    upCharge.setPrjId(projectid);
                    upCharge.setUserId(projectReqDTO.getInChargeUserId());
                    upCharge.setPrjRole("PRRO2");
                    userWriteMapper.insertUserProjectSelective(upCharge);
                }

                //增加城市经理
                if (projectReqDTO.getDistrictUserId() != null) {
                    UserProject upDistrict = new UserProject();
                    upDistrict.setPrjId(projectid);
                    upDistrict.setUserId(projectReqDTO.getDistrictUserId());
                    upDistrict.setPrjRole("PRRO3");
                    userWriteMapper.insertUserProjectSelective(upDistrict);
                }

                //创建项目自动添加权限
                UserProject upDistrict = new UserProject();
                upDistrict.setPrjId(projectid);
                upDistrict.setUserId(userId);
                upDistrict.setPrjRole("PRRO4");
                userWriteMapper.insertUserProjectSelective(upDistrict);
            }

            CodeReference codeReference;
            //统一设置装修风格/设备/竞品信息
            for (String code : codeList) {
                codeReference = new CodeReference();
                codeReference.setObjectId(projectid);
                codeReference.setSystemCode(code);
                codeReference.setType(TYPE);
                codeReference.updateCommonInfo(userId);
                codeReferenceWriteMapper.insertSelective(codeReference);
            }
        }
    }


    /**
     * 获取项目详情
     *
     * @param projectId
     * @return
     */
    @Override
    public ProjectDetailDTO getProjectDetail(Integer projectId) {

        ProjectDetailDTO result = new ProjectDetailDTO();
        result = projectReadMapper.getProjectDetail(projectId);
        //获取项目下的小区
        List<Estate> estateList = estateReadMapper.selectByProjectid(projectId);
        List<Map<String, Object>> service = codeReferenceReadMapper.getCodeRefByPCode(projectId, "_LPD", TYPE);//朗诗服务_LPD
        List<Map<String, Object>> style = codeReferenceReadMapper.getCodeRefByPCode(projectId, "_LPC", TYPE);//装修风格_LPC
        List<Map<String, Object>> facility = codeReferenceReadMapper.getCodeRefByPCode(projectId, "_LDD", TYPE); //设备_LD code
//        List<Map<String,Object>> competition = codeReferenceReadMapper.getCodeRefByPCode(projectId, "_LPE", TYPE);//竞品信息_LPE等信息 code
        result.setFacilityList(facility);
        result.setServiceList(service);
        result.setDecorativeStyleList(style);
        result.setEstateList(estateList);
//        result.setCompetition(result.getCompetition());

        //截取获得租期
        if (!"".equals(result.getLease()) && null != result.getLease()) {
            String str = result.getLease();
            String[] s1 = str.split(",");
            List<Map<String, Object>> leList = new ArrayList<Map<String, Object>>();
            for (int a = 0; a < s1.length; a++) {
                Map<String, Object> leMap = new HashMap<String, Object>();
                Code code = codeReadMapper.selectByPrimaryKey(s1[a]);
                leMap.put("code", code.getCode());
                leMap.put("codeDescZh", code.getCodeDescZh());
                leList.add(leMap);
            }
            result.setLeaseList(leList);
        }

        //截取获得付租方式
        if (!"".equals(result.getPaymentMode()) && null != result.getPaymentMode()) {
            String strp = result.getPaymentMode();
            String[] s1p = strp.split(",");
            List<Map<String, Object>> paList = new ArrayList<Map<String, Object>>();
            for (int a = 0; a < s1p.length; a++) {
                Map<String, Object> paMap = new HashMap<String, Object>();
                Code code = codeReadMapper.selectByPrimaryKey(s1p[a]);
                if(null != code) {
                    paMap.put("code", code.getCode());
                    paMap.put("codeDescZh", code.getCodeDescZh());
                    paList.add(paMap);
                } else {
                    continue;
                }

            }
            result.setPaymentModeList(paList);
        }

        return result;
    }

    /**
     * 获取项目详情：网站微信端
     *
     * @param id
     * @return
     */
    @Override
    public ProjectDetailForFrontDTO getProjectDetailForFront(Integer id) throws BusinessException {
        Project project = projectReadMapper.selectByPrimaryKey(id);
        ProjectDetailForFrontDTO result = new ProjectDetailForFrontDTO();
        ProjectDetailForFrontDTO terrresult = projectReadMapper.getProjectDetailForFront(id);
        terrresult.setWholeSceneUrl(project.getWholeSceneUrl());
        result = (terrresult == null) ? new ProjectDetailForFrontDTO() : terrresult;
        List<Map<String, Object>> roomTypeList = new ArrayList<>();
        List<Map<String, Object>> facility = codeReferenceReadMapper.getCodeRefByPCode(id, "_LDD", TYPE); //设备_LD code
        List<Map<String, Object>> style = codeReferenceReadMapper.getCodeRefByPCode(id, "_LPC", TYPE);//装修风格_LPC
        List<Configuration> facilities = new ArrayList<>();
        List<SystemFile> detailImgs = new ArrayList<>();
        for (String imgid : project.getDetailImages().split(",")) {
            SystemFile img = (SystemFile) fileService.get(imgid);
            detailImgs.add(img);
        }

        List<SystemFile> publicImgs = new ArrayList<>();
        for (String imgid : project.getPublicImages().split(",")) {
            SystemFile img = (SystemFile) fileService.get(imgid);
            publicImgs.add(img);
        }

        //项目设备对应配置
        for (Map m : facility) {
            String code = (String) m.get("code");
            Configuration configuration = configurationReadMapper.selectByPrimaryKey(code);
            configuration.setValue(this.getUrl(configuration.getValue()));
            facilities.add(configuration);
        }

        //房型信息
        if (null != style) {
            for (Map m : style) {
                String code = (String) m.get("code");
                RoomType roomType = roomTypeReadMapper.selectByPrjIdAndCode(id, code);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("title", m.get("zhDesc"));
                map.put("roomType", roomType);

                if (null != roomType) {
                    String[] split = roomType.getFacility().split(",");
                    List<Configuration> roomFacilities = new ArrayList<>();
                    List<SystemFile> imgs = new ArrayList<>();

                    for (String s : split) {
                        Configuration configuration = configurationReadMapper.selectByPrimaryKey(s);
                        if (configuration != null) {
                            configuration.setValue(this.getUrl(configuration.getValue()));
                            roomFacilities.add(configuration);
                        }
                    }

                    String[] split1 = roomType.getDetailImages().split(",");

                    for (String ss : split1) {
                        SystemFile systemFile = (SystemFile) fileService.get(ss);
                        imgs.add(systemFile);
                    }
                    map.put("imgs", imgs);
                    map.put("facilities", roomFacilities);   //房型设备
                    roomTypeList.add(map);
                }
            }
        }

        result.setDetailImgs(detailImgs);
        result.setPublicImgs(publicImgs);
        result.setFacilities(facilities);
        result.setRoomTypeList(roomTypeList);
        return result;
    }

    /**
     * 项目列表：网站和微信端
     *
     * @param areaCode
     * @return
     */
    @Override
    public List<Map<String, String>> getProjectListForFront(String areaCode, Integer isClassics) throws BusinessException {
        List<Map<String, String>> projectListForFront = projectReadMapper.getProjectListForFront(areaCode, isClassics);
        for (Map m : projectListForFront) {
            Integer coverImageId = (Integer) m.get("coverImage"); //项目封面图片
            SystemFile systemFile = (SystemFile) fileService.get(coverImageId + "");
            if (systemFile != null) { //Add validation by Daniel on 20170627
                String fullPath = systemFile.getFullPath();
                m.put("coverImageSrc", fullPath);
            }

            Integer prjId = (Integer) m.get("prjId");
            List<Map<String, Object>> style = codeReferenceReadMapper.getCodeRefByPCode(prjId, "_LPC", TYPE);//装修风格_LPC
            m.put("roomtype", style);
            String projectRoomStyle = (String) m.get("projectRoomStyle");
            if (!StringUtils.isEmpty(projectRoomStyle)) {
                m.put("roomStyleZh", codeReferenceReadMapper.getZhRefByCodes(java.util.Arrays.asList(projectRoomStyle.split(","))));
            }
            String paymentMode = (String) m.get("paymentMode");
            if (!StringUtils.isEmpty(paymentMode)) {
                m.put("paymentModeZh", codeReferenceReadMapper.getZhRefByCodes(java.util.Arrays.asList(paymentMode.split(","))));
            }
            String lease = (String) m.get("lease");
            if (!StringUtils.isEmpty(lease)) {
                m.put("leaseZh", codeReferenceReadMapper.getZhRefByCodes(java.util.Arrays.asList(lease.split(","))));
            }
        }
        return projectListForFront;
    }

    /**
     * 项目列表：后台
     *
     * @param areaCode
     * @return
     */
    @Override
    public List<Map<String, String>> getProjectListForBackend(String areaCode, Integer isClassics) throws BusinessException {
        List<Map<String, String>> projectListForFront = projectReadMapper.getProjectListForBackend(areaCode, isClassics);
        for (Map m : projectListForFront) {
            Integer coverImageId = (Integer) m.get("coverImage"); //项目封面图片
            SystemFile systemFile = (SystemFile) fileService.get(coverImageId + "");
            if (systemFile != null) {
                String fullPath = systemFile.getFullPath();
                m.put("coverImageSrc", fullPath);
            }
            Integer prjId = (Integer) m.get("prjId");
            List<Map<String, Object>> style = codeReferenceReadMapper.getCodeRefByPCode(prjId, "_LPC", TYPE);//装修风格_LPC
            m.put("roomtype", style);
            String projectRoomStyle = (String) m.get("projectRoomStyle");
            if (!StringUtils.isEmpty(projectRoomStyle)) {
                m.put("roomStyleZh", codeReferenceReadMapper.getZhRefByCodes(java.util.Arrays.asList(projectRoomStyle.split(","))));
            }
            String paymentMode = (String) m.get("paymentMode");
            if (!StringUtils.isEmpty(paymentMode)) {
                m.put("paymentModeZh", codeReferenceReadMapper.getZhRefByCodes(java.util.Arrays.asList(paymentMode.split(","))));
            }
            String lease = (String) m.get("lease");
            if (!StringUtils.isEmpty(lease)) {
                m.put("leaseZh", codeReferenceReadMapper.getZhRefByCodes(java.util.Arrays.asList(lease.split(","))));
            }
        }
        return projectListForFront;
    }

    @Override
    public List<Map<String, String>> getProjectInfoWithArea() {
        List<Map<String, String>> terr = projectReadMapper.getProjectInfoWithArea();
        return terr;
    }

    @Override
    public Boolean validate(Object o) throws BusinessException {
        return null;
    }

    @Override
    public Boolean validateForInsert(Object obj) throws BusinessException {

        boolean retValue = false;
        ProjectReqDTO projectReqDTO = null;

        if (obj == null) {

        } else {
            projectReqDTO = (ProjectReqDTO) obj;
            if (StringUtils.isEmpty(projectReqDTO.getPrjName())) {
                throw new LandseaBusinessException("请输入项目名称！！");
            }
          /*  if (StringUtils.isEmpty(projectReqDTO.getArea())) {
                throw new LandseaBusinessException("请输入建筑面积！！");
            }
            if (StringUtils.isEmpty(projectReqDTO.getCoverImage())) {
                throw new LandseaBusinessException("请上传首页图片！！");
            }
            if (StringUtils.isEmpty(projectReqDTO.getDetailImages())) {
                throw new LandseaBusinessException("请上传详情图片！！");
            }
            if (StringUtils.isEmpty(projectReqDTO.getDesc())) {
                throw new LandseaBusinessException("请输入项目描述！！");
            }
            if (StringUtils.isEmpty(projectReqDTO.getIsClassics())) {
                throw new LandseaBusinessException("请输入是否为经典项目！！");
            }
            if (StringUtils.isEmpty(projectReqDTO.getDistrictUserId())) {
                throw new LandseaBusinessException("请选择城市负责人！！");
            }
            if (StringUtils.isEmpty(projectReqDTO.getInChargeUserId())) {
                throw new LandseaBusinessException("请选择店长！！");
            }
            if (StringUtils.isEmpty(projectReqDTO.getUnitCount())) {
                throw new LandseaBusinessException("请输入单元数");
            }
            if (StringUtils.isEmpty(projectReqDTO.getFloorCount())) {
                throw new LandseaBusinessException("请输入楼层数");
            }
            if (StringUtils.isEmpty(projectReqDTO.getTotalApartmentsCount())) {
                throw new LandseaBusinessException("请输入总房间数");
            }*/
            if (StringUtils.isEmpty(projectReqDTO.getSourceType())) {
                throw new LandseaBusinessException("请选择项目来源");
            }
            //updated by Daniel for fix phone is not required
//            if (StringUtils.isEmpty(projectReqDTO.getTelephone())) {
//                throw new LandseaBusinessException("请输入固定电话！！");
//            }
/*            if (StringUtils.isEmpty(projectReqDTO.getTrafficInfo())) {
                throw new LandseaBusinessException("请输入交通信息！！");
            }
            if (StringUtils.isEmpty(projectReqDTO.getPublicDesc())) {
                throw new LandseaBusinessException("请输入公区设备描述！！");
            }
            if (StringUtils.isEmpty(projectReqDTO.getCommercialFacility())) {
                throw new LandseaBusinessException("请输入商业配套描述！！");
            }*/
        }
        return Boolean.valueOf(true);
    }

    @Override
    public Boolean validateForUpdate(Object obj) throws BusinessException {

        boolean retValue = false;
        Project project = null;

        if (obj == null) {

        } else {
            project = (Project) obj;
            //项目状态关闭之前过限制房间空置的状态
            if ("LPA3".equals(project.getStatus())) {
                Integer prjId = project.getId();
                List<ProjectAppartmentDTO> paList = roomReadMapper.selectByPrjId(prjId);
                if (paList.size() > 0) {
                    for (int i = 0; i < paList.size(); i++) {
                        ProjectAppartmentDTO pad = paList.get(i);
                        String status = pad.getAppendStatus();
                        if ("LRB1".equals(status)) {
                            throw new LandseaBusinessException("该项目下有空置状态的房间，无法关闭。");
                        }
                    }
                }
            }
            if (StringUtils.isEmpty(project.getId())) {
                throw new LandseaBusinessException("项目id不能为空");
            }
        }
        return Boolean.valueOf(true);
    }

    @Override
    public Boolean validateForDelete(Object o) throws BusinessException {
        return null;
    }

    public void setEstateByProjectReqDTO(Estate estate, ProjectReqDTO projectReqDTO, Integer userId) {
        if (projectReqDTO.getArea() != null && !"".equals(projectReqDTO.getArea()))
            estate.setBuildArea(new BigDecimal(projectReqDTO.getArea()));
        if (projectReqDTO.getUnitCount() != null)
            estate.setUnitCount(projectReqDTO.getUnitCount());
        if (projectReqDTO.getFloorCount() != null)
            estate.setFloorCount(projectReqDTO.getFloorCount());
        estate.updateCommonInfo(userId);
    }

    public void setAddressByProjectReqDTO(Address address, ProjectReqDTO projectReqDTO, Integer userId) {

        if (projectReqDTO.getProvince() != null)
            address.setProvince(projectReqDTO.getProvince());
        if (projectReqDTO.getCity() != null)
            address.setCity(projectReqDTO.getCity());
        if (projectReqDTO.getCounty() != null)
            address.setCounty(projectReqDTO.getCounty());
        if (projectReqDTO.getAddress() != null)
            address.setAddressLine1(projectReqDTO.getAddress());
        address.setCountry(COUNTRY_CODE);
        address.updateCommonInfo(userId);
       /* address.setLastModifiedDtm(new Timestamp((new Date()).getTime()));
        if(currentLogin.getUserId()!=null)
        address.setLastModifiedBy(currentLogin.getUserId());*/
    }


    public void setProjectByProjectReqDTO(Project project, ProjectReqDTO projectReqDTO, Integer userId) {

        if (projectReqDTO.getPrjName() != null)
            project.setPrjName(projectReqDTO.getPrjName());

        if (projectReqDTO.getDesc() != null)
            project.setBriefDesc(projectReqDTO.getDesc());
        if (projectReqDTO.getIsClassics() != null)
            project.setIsClassics(projectReqDTO.getIsClassics());
        if (projectReqDTO.getDistrictUserId() != null)
            project.setDistrictUserId(projectReqDTO.getDistrictUserId());
        if (projectReqDTO.getInChargeUserId() != null)
            project.setInChargeUserId(projectReqDTO.getInChargeUserId());
        if (projectReqDTO.getIsDistributed() != null)
            project.setIsDistributed(projectReqDTO.getIsDistributed());
        if (projectReqDTO.getHousekeeperId() != null)
            project.setHousekeeperId(projectReqDTO.getHousekeeperId());
        if (projectReqDTO.getOnlineTime() != null)
            project.setOnlineTime(projectReqDTO.getOnlineTime());
        if (projectReqDTO.getPrice() != null && !"".equals(projectReqDTO.getPrice()))
            project.setPrice(new BigDecimal(projectReqDTO.getPrice()));

        //默认草稿
        if (StringUtils.isEmpty(projectReqDTO.getStatus()) && StringUtils.isEmpty(project.getStatus())) {
            project.setStatus("LPA1");
        }/*else{
            project.setStatus(projectReqDTO.getStatus());
        }*/
        //默认装修
        if (StringUtils.isEmpty(projectReqDTO.getManageStatus()) && StringUtils.isEmpty(project.getManageStatus())) {
            project.setManageStatus("LPB1");
        }/*else{
            project.setManageStatus(projectReqDTO.getManageStatus());

        }*/
        if (projectReqDTO.getSourceType() != null)
            project.setSourceType(projectReqDTO.getSourceType());
        if (projectReqDTO.getTotalApartmentsCount() != null)
            project.setTotalApartmentsCount(projectReqDTO.getTotalApartmentsCount());
        if (projectReqDTO.getOrganizationId() != null)
            project.setOrganizationId(projectReqDTO.getOrganizationId());
        if (projectReqDTO.getTrafficBus() != null)
            project.setTrafficBus(projectReqDTO.getTrafficBus());
        if (projectReqDTO.getTrafficSubway() != null)
            project.setTrafficSubway(projectReqDTO.getTrafficSubway());
        if (projectReqDTO.getTrafficRoad() != null)
            project.setTrafficRoad(projectReqDTO.getTrafficRoad());
        if (projectReqDTO.getTrafficOther() != null)
            project.setTrafficOther(projectReqDTO.getTrafficOther());
        if (projectReqDTO.getCoverImage() != null)
            project.setCoverImage(projectReqDTO.getCoverImage());
        if (projectReqDTO.getDetailImages() != null)
            project.setDetailImages(projectReqDTO.getDetailImages());
        if (projectReqDTO.getPublicImages() != null)
            project.setPublicImages(projectReqDTO.getPublicImages());
        if (projectReqDTO.getWholeSceneUrl() != null)
            project.setWholeSceneUrl(projectReqDTO.getWholeSceneUrl());
        if (projectReqDTO.getAreaCode() != null)
            project.setAreaCode(projectReqDTO.getAreaCode());
        if (projectReqDTO.getTelephone() != null)
            project.setTelephone(projectReqDTO.getTelephone());
        if (projectReqDTO.getTrafficInfo() != null)
            project.setTrafficInfo(projectReqDTO.getTrafficInfo());
        if (projectReqDTO.getPublicDesc() != null)
            project.setPublicDesc(projectReqDTO.getPublicDesc());
        if (projectReqDTO.getCommercialFacility() != null)
            project.setCommercialFacility(projectReqDTO.getCommercialFacility());
        project.setLastModifiedBy(userId);

        project.setVersion(1);
        if (projectReqDTO.getCostType() != null)
            project.setCostType(projectReqDTO.getCostType());
        if (projectReqDTO.getAccountCostType() != null)
            project.setAccountCostType(projectReqDTO.getAccountCostType());
        if (projectReqDTO.getDepositAmount() != null)
            project.setDepositAmount(projectReqDTO.getDepositAmount());
        if (projectReqDTO.getTermOfValidity() != null)
            project.setTermOfValidity(projectReqDTO.getTermOfValidity());
        if (projectReqDTO.getPaymentMode() != null)
            project.setPaymentMode(projectReqDTO.getPaymentMode());
        if (projectReqDTO.getLease() != null)
            project.setLease(projectReqDTO.getLease());
        if (projectReqDTO.getWaterPrice() != null)
            project.setWaterPrice(projectReqDTO.getWaterPrice());
        if (projectReqDTO.getElectricPrice() != null)
            project.setElectricPrice(projectReqDTO.getElectricPrice());
        if (projectReqDTO.getGasPrice() != null)
            project.setGasPrice(projectReqDTO.getGasPrice());
        if (projectReqDTO.getHotWaterPrice() != null)
            project.setHotWaterPrice(projectReqDTO.getHotWaterPrice());
        if (projectReqDTO.getParkPrice() != null)
            project.setParkPrice(projectReqDTO.getParkPrice());
        if (projectReqDTO.getAirConditionerPrice() != null)
            project.setAirConditionerPrice(projectReqDTO.getAirConditionerPrice());
        if (projectReqDTO.getHeatingPrice() != null)
            project.setHeatingPrice(projectReqDTO.getHeatingPrice());
        if (projectReqDTO.getCompetition() != null)
            project.setCompetition(projectReqDTO.getCompetition());
        if (projectReqDTO.getDepositWater() != null)
            project.setDepositWater(projectReqDTO.getDepositWater());
        if (projectReqDTO.getContractAddress() != null)
            project.setContractAddress(projectReqDTO.getContractAddress());
        if (projectReqDTO.getContractName() != null)
            project.setContractName(projectReqDTO.getContractName());
        if (projectReqDTO.getContractPhone() != null)
            project.setContractPhone(projectReqDTO.getContractPhone());
        if (projectReqDTO.getMerchantId() != null)
            project.setMerchantId(projectReqDTO.getMerchantId());
        if (projectReqDTO.getMerchantName() != null)
            project.setMerchantName(projectReqDTO.getMerchantName());
        if (projectReqDTO.getMerchantAbbreviation() != null)
            project.setMerchantAbbreviation(projectReqDTO.getMerchantAbbreviation());
        if (projectReqDTO.getPublicStatus() != null)
            project.setPublicStatus(projectReqDTO.getPublicStatus());
        project.updateCommonInfo(userId);
    }


    @Override
    public KeeperDTO getKeeper(String areaCode) {
        KeeperDTO keeper = new KeeperDTO();
        keeper.setAreaCode(areaCode);
        List<PeopleInfo> shopkeeper = projectReadMapper.getShopKeeper(areaCode);
        keeper.setShopkeeper(shopkeeper);
        List<PeopleInfo> citykeeper = projectReadMapper.getCityKeeper(areaCode);
        keeper.setCitykeeper(citykeeper);
        List<PeopleInfo> housekeeper = projectReadMapper.getHouseKeeper(areaCode);
        keeper.setHousekeeper(housekeeper);
        return keeper;
    }


    @Override
    public List<ExpenseDTO> getBaseInfo(Integer contractId) throws BusinessException {
        List<ExpenseDTO> expenseDTOList = new ArrayList<>();
        ContractDTO contractDTO = (ContractDTO) contractServiceImpl.get(contractId);
        ProjectDetailDTO result = projectReadMapper.getProjectDetail(contractDTO.getProjectId());
        String costTypes = result.getCostType();
        if (costTypes != null) {
            String[] costTypeArray = costTypes.split(",");
            for (String costType : costTypeArray) {
                ExpenseDTO expenseDTO = new ExpenseDTO();
                expenseDTO.setType(costType);
                Code code = codeReadMapper.selectByPrimaryKey(costType);
                expenseDTO.setTypeDesc(code.getCodeDescZh());
                Double price = getPriceByExpenseType(costType, result);
                expenseDTO.setPrice(price);
                expenseDTOList.add(expenseDTO);
            }
        }
        return expenseDTOList;
    }


    private Double getPriceByExpenseType(String expenseType, ProjectDetailDTO result) {
        Double price = null;
        if (BillTypeEnum.CTBI5.getCode().equalsIgnoreCase(expenseType)) {
            price = result.getParkPrice();
        } else if (BillTypeEnum.CTBI6.getCode().equalsIgnoreCase(expenseType)) {
            price = result.getAirConditionerPrice();
        } else if (BillTypeEnum.CTBI7.getCode().equalsIgnoreCase(expenseType)) {
            price = result.getHeatingPrice();
        }
        return price;
    }

    @Override
    public List<ExpenseDTO> getBaseInfoByPrjId(FeePrjDTO dto) throws BusinessException {
        List<ExpenseDTO> expenseDTOList = new ArrayList<>();
        if(dto.getPrjId()==null || dto.getPrjId()==0){
            throw new LandseaBusinessException("项目id不能为空");
        }
        if(StringUtils.isEmpty(dto.getType())){
            throw new LandseaBusinessException("查询类型不能为空");
        }
        ProjectDetailDTO result = projectReadMapper.getProjectDetail(dto.getPrjId());
        String costTypes = result.getCostType();
        if (costTypes != null) {
            String[] costTypeArray = costTypes.split(",");
            for (String costType : costTypeArray) {
                //如果是智能电，则电不再返回给前台
                if(dto.getType().equals("import")){
                    if (costType.equals(BillTypeEnum.CTBI2.getCode()) && !StringUtils.isEmpty(result.getSmartEle())) {
                        continue;
                    }
                }
                ExpenseDTO expenseDTO = new ExpenseDTO();
                expenseDTO.setType(costType);
                Code code = codeReadMapper.selectByPrimaryKey(costType);
                expenseDTO.setTypeDesc(code.getCodeDescZh());
                // Double price = getPriceByExpenseType(costType, result);
                //expenseDTO.setPrice(price);
                expenseDTOList.add(expenseDTO);
            }
        }
        return expenseDTOList;
    }

}
